package com.ugoodtech.mdcc.web.service.impl;

        /* Copyright (C) Ugoodtech, Inc - All Rights Reserved
         * Unauthorized copying of this file, via any medium is strictly prohibited
         * Proprietary and confidential
         */

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.web.dto.JsonException;
import com.ugoodtech.mdcc.web.service.UserLogService;
import com.ugoodtech.mdcc.web.service.UserProfileService;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserLogServiceImpl implements UserLogService {

    @Autowired
    private UserLogRepository userLogRepository;
    @Autowired
    private UserProfileService userProfileService;
    @Autowired
    private UserProfileRepository userProfileRepository;
    @Autowired
    private StationRepository stationRepository;
    @Autowired
    private AuditColorReportRepository auditColorReportRepository;
    @Autowired
    private AuditReportRepository auditReportRepository;
    @Autowired
    private StationColorReportRepository stationColorReportRepository;
    @Autowired
    private StationReportRepository stationReportRepository;


    private static Logger logger = LoggerFactory.getLogger(UserLogServiceImpl.class);

    @Override
    public UserLog addUserLog(User user, String stationNum, String operateType, String businessType, Long dataId, Map<String, Object> data) {
        UserLog userLog = null;
        try {
            isUserLogin();
            userLog = new UserLog();
            userLog.setPlatform("中台");
            userLog.setUser(user);
            userLog.setOperateType(operateType);
            userLog.setBusinessType(businessType);
            userLog.setUser(user);
            HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            userLog.setOperateIp(httpServletRequest.getRemoteAddr());
            if (null != user) {
                UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
                userLog.setName(userProfile.getRealName());
            }
            if (StringUtils.isNotEmpty(stationNum)) {
                try {
                    Station station = stationRepository.findByStationNum(stationNum);
                    if(null!=station){
                        userLog.setStationNo(station.getStationNum());
                        userLog.setStationName(station.getName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            userLog.setOperateDataId(dataId);
            if (null != data) {
                if (null != data.get("str")) {
                    String str = data.get("str") + "";
                    userLog.setOperateDesc(str.replace(",", ",\r\n<br>"));
                }
            }
            userLogRepository.save(userLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userLog;
    }

    @Override
    public UserLog addUserLog(User user, String stationNum, String operateType, String businessType, Long dataId, Map<String, Object> data, HttpServletRequest request) {
        UserLog userLog = null;
        try {
            isUserLogin();
            userLog = new UserLog();
            userLog.setPlatform("中台");
            userLog.setUser(user);
            userLog.setOperateType(operateType);
            userLog.setBusinessType(businessType);
            userLog.setUser(user);
            userLog.setOperateIp(request.getRemoteAddr());
            if (null != user) {
                UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
                userLog.setName(userProfile.getRealName());
            }
            if (StringUtils.isNotEmpty(stationNum)) {
                try {
                    Station station = stationRepository.findByStationNum(stationNum);
                    userLog.setStationNo(station.getStationNum());
                    userLog.setStationName(station.getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            userLog.setOperateDataId(dataId);
            if (null != data) {
                if (null != data.get("str")) {
                    String str = data.get("str") + "";
                    userLog.setOperateDesc(str.replace(",", ",\r\n<br>"));
                }
            }
            userLogRepository.save(userLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userLog;
    }

    @Override
    public UserLog addUserLog(User user, String stationNum, Long reportId, String category, String operateType, String businessType, Long dataId, Map<String, Object> data) {
        UserLog userLog = null;

        try {
            isUserLogin();
            userLog = new UserLog();
            userLog.setPlatform("中台");
            userLog.setUser(user);
            userLog.setOperateType(operateType);
            userLog.setBusinessType(businessType);
            userLog.setUser(user);
            HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            userLog.setOperateIp(httpServletRequest.getRemoteAddr());
            if (null != user) {
                UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
                userLog.setName(userProfile.getRealName());
            }

            if (StringUtils.isNotEmpty(stationNum)) {
                try {
                    Station station = stationRepository.findByStationNum(stationNum);
                    if(null!=station){
                        userLog.setStationNo(station.getStationNum());
                        userLog.setStationName(station.getName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            userLog.setOperateDataId(dataId);
            if (null != data) {
                if (null != data.get("str")) {
                    String str = data.get("str") + "";
                    userLog.setOperateDesc(str.replace(",", ",\r\n<br>"));
                }
            }
            if (reportId != null && reportId != 0) {
                userLog.setReportId(reportId);
            }
            if (StringUtils.isNotEmpty(category)) {
                userLog.setCategory(category);
            }
            userLogRepository.save(userLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userLog;
    }

    @Override
    public void setLogStation(UserLog userLog) {
        if (null != userLog) {
            String stationName = "";
            String stationNum = "";
            AuditColorReport auditColorReport = auditColorReportRepository.selectReport(userLog.getReportId(), 175L);
            AuditColorReport auditColorReportNum = auditColorReportRepository.selectReport(userLog.getReportId(), 181L);
            if (null != auditColorReport) {
                stationName = auditColorReport.getAnswerOther();
            }
            if (null != auditColorReportNum) {
                stationNum = auditColorReportNum.getAnswerOther();
            }
            userLog.setStationNo(stationNum);
            userLog.setStationName(stationName);
            userLogRepository.save(userLog);
        }
    }

    @Override
    public Page<UserLog> queryUserLogs(@ApiParam("开始时间") Long startDate,
                                       @ApiParam("结束时间") Long endDate,
                                       @ApiParam("人员姓名") String userName,
                                       @ApiParam("人员手机号") String phoneNumber,
                                       @ApiParam("维修站名称") String stationName,
                                       @ApiParam("IP地址") String ipAddress,
                                       @ApiParam("操作类型") String operateType,
                                       @ApiParam("业务类型") String businessType,
                                       @ApiParam("描述") String description,
                                       @ApiParam("报告类型") String category,
                                       @ApiParam("报告ID") Long reportId,
                                       @ApiParam("是否审核通过") Boolean audited,
                                       Pageable pageable) {
        QUserLog qUserLog = QUserLog.userLog;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserLog.deleted.eq(false));
        if (null != startDate) {
            builder.and(qUserLog.creationTime.before(new Date(startDate)).not());
        }
        if (null != endDate) {
            builder.and(qUserLog.creationTime.after(new Date(endDate)).not());
        }
        if (!StringUtils.isEmpty(userName)) {
            List<Long> userIds = userProfileService.queryLikeUserId(userName);
            builder.and(qUserLog.user.id.in(userIds));
        }
        if (!StringUtils.isEmpty(phoneNumber)) {
            builder.and(qUserLog.user.username.like("%" + phoneNumber + "%"));
        }
        if (!StringUtils.isEmpty(stationName)) {
            builder.and(qUserLog.stationName.like("%" + stationName + "%"));
        }
        if (!StringUtils.isEmpty(ipAddress)) {
            builder.and(qUserLog.operateIp.eq(ipAddress));
        }
        if (!StringUtils.isEmpty(operateType)) {
            if (operateType.startsWith("%") && operateType.endsWith("%")) {
                builder.and(qUserLog.operateType.like(operateType));
            } else if (operateType.equals(LogConstants.operate_type_edit + "/" + LogConstants.operate_type_manage_report)) {
                BooleanBuilder keyBuilder = new BooleanBuilder();
                keyBuilder.or(qUserLog.operateType.eq(LogConstants.operate_type_edit));
                keyBuilder.or(qUserLog.operateType.eq(LogConstants.operate_type_manage_report));
                builder.and(keyBuilder);
            } else {
                builder.and(qUserLog.operateType.eq(operateType));
            }
        }
        if (!StringUtils.isEmpty(businessType)) {
            if (businessType.startsWith("%") && businessType.endsWith("%")) {
                builder.and(qUserLog.businessType.like(businessType));
            } else {
                builder.and(qUserLog.businessType.eq(businessType));
            }
        }
        if (!StringUtils.isEmpty(description)) {
            builder.and(qUserLog.operateDesc.like("%" + description + "%"));
        }
        if (StringUtils.isNotEmpty(category)) {
            builder.and(qUserLog.category.like("%" + category + "%"));
        }
        if (reportId != null && reportId != 0) {
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            if(null!=audited&&audited){
                StationReport stationReport = stationReportRepository.findOne(reportId);
                if (null != stationReport) {
                    Station station = stationReport.getStation();
                    if (null != station) {
                        booleanBuilder.or(qUserLog.station.id.eq(station.getId()));
                        if (StringUtils.isNotEmpty(station.getName())) {
                            booleanBuilder.or(qUserLog.stationName.eq(station.getName()));
                        }
                    } else {
                        logger.info("此报告没有维修站");
                    }
                } else {
                    logger.info("没有此报告");
                }
            }else{
                AuditColorReport colorReport = auditColorReportRepository.selectReport(reportId, 175L);
                BooleanBuilder reportIdBuilder = new BooleanBuilder();
                reportIdBuilder.and(qUserLog.reportId.eq(reportId));
                reportIdBuilder.and(qUserLog.category.eq(Constants.CUSTOMER_REPORT));
                booleanBuilder.or(reportIdBuilder);
                if(null!=colorReport){
                    booleanBuilder.or(qUserLog.stationName.eq(colorReport.getAnswerOther()));
                }
            }
            builder.and(booleanBuilder);
        }
        Sort sort = new Sort(Sort.Direction.DESC, "creationTime","id");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<UserLog> userLogs = userLogRepository.findAll(builder, pageable);
        return userLogs;
    }

    protected User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal != null && principal instanceof User) {
            return (User) principal;
        } else {
            Object details = authentication.getDetails();
            if (details != null && details instanceof User) {
                return (User) details;
            }
        }
        return null;
    }

    public void isUserLogin() {
        if (null == this.getCurrentUser()) {
            throw new JsonException("notLogin");
        }
    }
}
